//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
using System.Web;
namespace DotNetNuke.Modules.Admin.Portals
{
	partial class Portals : Entities.Modules.PortalModuleBase, Entities.Modules.IActionable
	{
		private string _Filter = "";
		private int _CurrentPage = 1;
		private ArrayList _Portals = new ArrayList();
		protected int TotalPages = -1;
		protected int TotalRecords;
		protected int CurrentPage
		{
			get { return _CurrentPage; }
			set { _CurrentPage = value; }
		}
		protected string Filter
		{
			get { return _Filter; }
			set { _Filter = value; }
		}
		protected ArrayList PortalsList
		{
			get { return _Portals; }
			set { _Portals = value; }
		}
		protected int PageSize
		{
			get { return 20; }
		}
		protected bool SuppressPager
		{
			get { return true; }
		}
		private void BindData()
		{
			CreateLetterSearch();
			string strQuerystring = Null.NullString;
			if (!String.IsNullOrEmpty(Filter))
			{
				strQuerystring += "filter=" + Filter;
			}
			if (Filter == Localization.GetString("Expired", LocalResourceFile))
			{
				PortalsList = PortalController.GetExpiredPortals();
				ctlPagingControl.Visible = false;
			}
			else
			{
				PortalsList = PortalController.GetPortalsByName(Filter + "%", CurrentPage - 1, PageSize, ref TotalRecords);
			}
			grdPortals.DataSource = PortalsList;
			grdPortals.DataBind();
			ctlPagingControl.TotalRecords = TotalRecords;
			ctlPagingControl.PageSize = PageSize;
			ctlPagingControl.CurrentPage = CurrentPage;
			ctlPagingControl.QuerystringParams = strQuerystring;
			ctlPagingControl.TabID = TabId;
			if (SuppressPager && ctlPagingControl.Visible)
			{
				ctlPagingControl.Visible = (PageSize < TotalRecords);
			}
		}
		private void CreateLetterSearch()
		{
			string filters = Localization.GetString("Filter.Text", this.LocalResourceFile);
			filters += "," + Localization.GetString("All");
			filters += "," + Localization.GetString("Expired", LocalResourceFile);
			string[] strAlphabet = filters.Split(',');
			rptLetterSearch.DataSource = strAlphabet;
			rptLetterSearch.DataBind();
		}
		private void DeleteExpiredPortals()
		{
			try
			{
				CheckSecurity();
				PortalController.DeleteExpiredPortals(Common.Globals.GetAbsoluteServerPath(Request));
				BindData();
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}

		private void CheckSecurity()
		{
			// Verify that the current user has access to access this page
			if (!UserInfo.IsSuperUser)
			{
				Response.Redirect(DotNetNuke.Common.Globals.NavigateURL("Access Denied"), true);
			}
		}

		protected string FilterURL(string Filter, string CurrentPage)
		{
			string _URL = Null.NullString;
			if (!String.IsNullOrEmpty(Filter))
			{
				if (!String.IsNullOrEmpty(CurrentPage))
				{
					_URL = Common.Globals.NavigateURL(TabId, "", "filter=" + Filter, "currentpage=" + CurrentPage);
				}
				else
				{
					_URL = Common.Globals.NavigateURL(TabId, "", "filter=" + Filter);
				}
			}
			else
			{
				if (!String.IsNullOrEmpty(CurrentPage))
				{
					_URL = Common.Globals.NavigateURL(TabId, "", "currentpage=" + CurrentPage);
				}
				else
				{
					_URL = Common.Globals.NavigateURL(TabId, "");
				}
			}
			return _URL;
		}
		public string FormatExpiryDate(System.DateTime DateTime)
		{
			string strDate = string.Empty;
			try
			{
				if (!Null.IsNull(DateTime))
				{
					strDate = DateTime.ToShortDateString();
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return strDate;
		}
		public string FormatPortalAliases(int PortalID)
		{
			System.Text.StringBuilder str = new System.Text.StringBuilder();
			try
			{
				PortalAliasController objPortalAliasController = new PortalAliasController();
				ArrayList arr = objPortalAliasController.GetPortalAliasArrayByPortalID(PortalID);
				PortalAliasInfo objPortalAliasInfo;
				int i;
				for (i = 0; i <= arr.Count - 1; i++)
				{
					objPortalAliasInfo = (PortalAliasInfo)arr[i];

					string httpAlias = DotNetNuke.Common.Globals.AddHTTP(objPortalAliasInfo.HTTPAlias);
					string originalUrl = HttpContext.Current.Items["UrlRewrite:OriginalUrl"].ToString().ToLowerInvariant();

					httpAlias = DotNetNuke.Common.Globals.AddPort(httpAlias, originalUrl);

					str.Append("<a href=\"" + httpAlias + "\">" + objPortalAliasInfo.HTTPAlias + "</a>" + "<BR>");
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return str.ToString();
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			foreach (DataGridColumn column in grdPortals.Columns)
			{
				if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn)))
				{
					ImageCommandColumn imageColumn = (ImageCommandColumn)column;
					if (imageColumn.CommandName == "Delete")
					{
						imageColumn.OnClickJS = Localization.GetString("DeleteItem");
					}
					if (imageColumn.CommandName == "Edit")
					{
						string formatString = EditUrl("pid", "KEYFIELD", "Edit");
						formatString = formatString.Replace("KEYFIELD", "{0}");
						imageColumn.NavigateURLFormatString = formatString;
					}
					if (!String.IsNullOrEmpty(imageColumn.CommandName))
					{
						imageColumn.Text = Localization.GetString(imageColumn.CommandName, this.LocalResourceFile);
					}
				}
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			grdPortals.DeleteCommand += new DataGridCommandEventHandler(grdPortals_DeleteCommand);
			grdPortals.ItemDataBound += new DataGridItemEventHandler(grdPortals_ItemDataBound);

			try
			{
				AddActionHandler(ModuleAction_Click);
				CheckSecurity();
				if (!UserInfo.IsSuperUser)
				{
					Response.Redirect(Common.Globals.NavigateURL("Access Denied"), true);
				}
				if (Request.QueryString["CurrentPage"] != null)
				{
					CurrentPage = Convert.ToInt32(Request.QueryString["CurrentPage"]);
				}
				if (Request.QueryString["filter"] != null)
				{
					Filter = Request.QueryString["filter"];
				}
				if (Filter == Localization.GetString("All"))
				{
					Filter = "";
				}
				if (!Page.IsPostBack)
				{
					Localization.LocalizeDataGrid(ref grdPortals, this.LocalResourceFile);
					BindData();
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void ModuleAction_Click(object sender, ActionEventArgs e)
		{
			switch (e.Action.CommandArgument)
			{
				case "Delete":
					DeleteExpiredPortals();
					break;
			}
		}
		private void grdPortals_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try
			{
				CheckSecurity();
				PortalController objPortalController = new PortalController();
				PortalInfo portal = objPortalController.GetPortal(Int32.Parse(e.CommandArgument.ToString()));
				if (portal != null)
				{
					string strMessage = PortalController.DeletePortal(portal, Common.Globals.GetAbsoluteServerPath(Request));
					if (string.IsNullOrEmpty(strMessage))
					{
						Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
						objEventLog.AddLog("PortalName", portal.PortalName, PortalSettings, UserId, Services.Log.EventLog.EventLogController.EventLogType.PORTAL_DELETED);
						UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PortalDeleted", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
					}
					else
					{
						UI.Skins.Skin.AddModuleMessage(this, strMessage, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					}
				}
				BindData();
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		protected void grdPortals_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			DataGridItem item = e.Item;
			if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
			{
				System.Web.UI.Control imgColumnControl = item.Controls[1].Controls[0];
				if (imgColumnControl is ImageButton)
				{
					ImageButton delImage = (ImageButton)imgColumnControl;
					PortalInfo portal = (PortalInfo)item.DataItem;
					delImage.Visible = portal.PortalID != PortalSettings.PortalId;
				}
			}
		}
		public ModuleActionCollection ModuleActions
		{
			get
			{
				ModuleActionCollection Actions = new ModuleActionCollection();
				Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", EditUrl("Signup"), false, SecurityAccessLevel.Host, true, false);
				Actions.Add(GetNextActionID(), Localization.GetString("ExportTemplate.Action", LocalResourceFile), ModuleActionType.AddContent, "", "lt.gif", EditUrl("Template"), false, SecurityAccessLevel.Admin, true, false);
				Actions.Add(GetNextActionID(), Localization.GetString("DeleteExpired.Action", LocalResourceFile), ModuleActionType.AddContent, "Delete", "delete.gif", "", "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteItems.Confirm")) + "')", true, SecurityAccessLevel.Admin, true,
				false);
				return Actions;
			}
		}
	}
}
